<?php

namespace App\Listeners;

use App\Common\Constant\Params;
use App\Events\OrderAppointed;
use App\Events\OrderDelivered;
use App\Events\OrderEmployed;
use App\Models\Order;
use App\Models\OrderStatus;
use App\Notifications\OrderNotifications\OrderAppointedNotification;
use App\Notifications\OrderNotifications\OrderDeliveredFailedNotification;
use App\Notifications\OrderNotifications\OrderEmployedNotification;
use Illuminate\Cache\Events\CacheHit;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class OrderDeliveredListener implements ShouldQueue
{

    use InteractsWithQueue;

    public $queue = 'order';

    public $tries = 3;

    public $timeout = 30;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  CacheHit  $event
     * @return void
     */
    public function handle(OrderDelivered $event)
    {
        $order = Order::find($event->order_id);
        if(!$order){
            throw new \Exception('miss order');
        }

        if(!$order->status){
            throw new \Exception('miss order status');
        }

        if ($order->status->master_status == Params::ORDER_MASTER_STATUS_LOGISTICS_FAILED){
            $order->merchant->notify(new OrderDeliveredFailedNotification($order));
        }
    }

    public function failed(OrderDelivered $event, \Exception $exception)
    {
        //
    }
}
